package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.config.RequestDataHelper;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.ExcelUtils;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.SurveyUserRecord;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.module.service.SurveyUserRecordService;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 问卷记录列表
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2021-11-5 12:36:23
 */
@Controller
@RequestMapping("/module/survey/record")
public class SurveyUserRecordController extends BaseController {
    @Resource
    private SurveyUserRecordService userRecordService;
    @Resource
    private SurveyUserRecordInfoService userRecordInfoService;
    @Resource
    private UserService userService;
    @Resource
    private TownsService townsService;
    @Resource
    private SurveyQuestionService surveyQuestionService;
    @Resource
    private SurveyService surveyService;
    @Value("${projecturl.imgurl}")
    private String imgUrl;//图片地址

    @Log("查询问卷记录列表页面")
    @GetMapping("/{surveyId}")
    @RequiresPermissions("module:survey:survey")
    String record(Model model,@PathVariable("surveyId") Integer surveyId) {
        UserDO user = getUser();
        model.addAttribute("surveyId",surveyId);
        QueryWrapper<Towns> qw = new QueryWrapper<>();
        qw.eq("district_id", 1319);
        qw.eq("state",1);
        qw.eq("parent_id",0);
        if(user.getUserLevel() !=null && user.getUserType() == 7){
            if(user.getUserLevel() == 2 || user.getUserLevel() == 3){//镇
                qw.eq("id",user.getTownId());
            }
        }
        List<Towns> towns = townsService.list(qw);
        List<Towns> villages = townsService.selectListByColumn("parent_id",towns.get(0).getId());
        model.addAttribute("towns",towns);
        model.addAttribute("villages",villages);


        model.addAttribute("begin_date",DateUtils.getDateByDaysStr(new Date(),-7));
        model.addAttribute("end_date",DateUtils.getDay());

        return "module/survey/record/record";
    }


    @Log("查询设备页面")
    @GetMapping("/info/{surveyId}/{recordId}")
    @RequiresPermissions("module:survey:survey")
    String recordInfo(Model model,@PathVariable("surveyId") Integer surveyId, @PathVariable("recordId") Integer recordId) {
        model.addAttribute("surveyId",surveyId);
        model.addAttribute("recordId",recordId);

        model.addAttribute("begin_date",DateUtils.getDateByDaysStr(new Date(),-7));
        model.addAttribute("end_date",DateUtils.getDay());
        return "module/survey/record/info";
    }

    @Log("查询问卷记录列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:survey:survey")
    public DataTableLayUI<SurveyUserRecord> list(DataTableLayUI<SurveyUserRecord> condition) {
        UserDO user = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String surveyId = map.containsKey("search_eq_surveyId") ? map.get("search_eq_surveyId").toString(): null;
        String townId = map.containsKey("search_eq_townId") ? map.get("search_eq_townId").toString(): null;
        String villageId = map.containsKey("search_eq_villageId") ? map.get("search_eq_villageId").toString(): null;
        String keyword = map.containsKey("search_like_keyword") ? map.get("search_like_keyword").toString(): null;
        String begin_date = map.containsKey("begin_date") ? map.get("begin_date").toString(): null;
        String end_date = map.containsKey("end_date") ? map.get("end_date").toString(): null;
        QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();

        Map<String,Object> mapParam = new HashMap<>();
        if(StrUtil.isNotEmpty(surveyId)){
            qw.eq("survey_id",surveyId);
            mapParam.put("survey_id",surveyId);
        }

        if(user.getUserType() == 7){
            if(user.getUserLevel() == 2){//镇
//                map.put("search_eq_townId",user.getTownId());
                qw.eq("town_id",user.getTownId());
                mapParam.put("town_id",user.getTownId());
                if(StrUtil.isNotEmpty(villageId)){
                    qw.eq("village_id",villageId);
                    mapParam.put("village_id",villageId);
                }
            }else if(user.getUserLevel() == 3){//村
//                map.put("search_eq_villageId",user.getVillageId());
                qw.eq("village_id",user.getVillageId());
                mapParam.put("village_id",user.getVillageId());
            }else{
                if(StrUtil.isNotEmpty(townId)){
                    qw.eq("town_id",townId);
                    mapParam.put("town_id",townId);
                }
                if(StrUtil.isNotEmpty(villageId)){
                    qw.eq("village_id",villageId);
                    mapParam.put("village_id",villageId);
                }
            }
        }else{
            if(StrUtil.isNotEmpty(townId)){
                qw.eq("town_id",townId);
                mapParam.put("town_id",townId);
            }
            if(StrUtil.isNotEmpty(villageId)){
                qw.eq("village_id",villageId);
                mapParam.put("village_id",villageId);
            }
        }

        if(StrUtil.isNotEmpty(keyword)){
            qw.like("holder_name",keyword);
            mapParam.put("keyWord",keyword);
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time",begin_date,end_date);
            mapParam.put("begin_time",begin_date);
            mapParam.put("end_time",end_date);
        }
//        condition.setQw(qw);

        Page<SurveyUserRecord> page = userRecordService.getPage(condition);
        List<SurveyUserRecord> list = userRecordService.getPageByUserId(page,mapParam);
        DataTableLayUI<SurveyUserRecord> dt = userRecordService.pageSearchCustom(page,list,condition);

//        DataTableLayUI<SurveyUserRecord> dt = userRecordService.pageSearchLayUI(condition);
//        List<SurveyUserRecord> list = dt.getData();
        list.forEach(record->{
            Towns town = townsService.findById(record.getTownId());
            if(town!=null){
                record.setTownName(town.getTownName());
            }
            Towns village = townsService.findById(record.getVillageId());
            if(village!=null){
                record.setVillageName(village.getTownName());
            }
            UserDO manger = userService.findById(record.getSysUserId());
            if(manger!=null){
                record.setManagerName(manger.getName());
                record.setManagerPhone(manger.getMobile());
            }
        });
        return dt;
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list/info")
    @RequiresPermissions("module:survey:survey")
    public DataTableLayUI<SurveyUserRecordInfo> listInfo(DataTableLayUI<SurveyUserRecordInfo> condition) {

        Map<String,Object> map = condition.getSearchParams();
        String recordId = map.containsKey("search_eq_recordId") ? map.get("search_eq_recordId").toString(): null;

        //判断当前是否需要重置 记录表
        String tableName = "";
        if(StrUtil.isNotEmpty(recordId)){
            SurveyUserRecord record = userRecordService.findById(recordId);
            if(record != null){
                tableName = record.getRecordTableName();
            }
            // 配置表名
            Map<String,Object> mapTable = new HashMap<>();
            mapTable.put("survey_user_record_info", tableName);
            RequestDataHelper.setRequestData(mapTable);
        }

        DataTableLayUI<SurveyUserRecordInfo> dt = userRecordInfoService.pageSearchLayUI(condition);
        List<SurveyUserRecordInfo> list = dt.getData();
        list.forEach(recordInfo->{
            SurveyQuestion question = surveyQuestionService.findById(recordInfo.getQuestionId());
            if(question!=null){
                recordInfo.setQuestion(question.getQuestion());
                recordInfo.setQuestionTitle(question.getQuestion());
                if(question.getQuestionType() == 0){//单选题
                    if(StrUtil.isNotEmpty(question.getAnswerSection())){
                        JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                        if(jsonArray.size() > 0){
                            Integer answer = Integer.parseInt(recordInfo.getAnswer());
                            List<String> answers = new ArrayList<>();
                            for (int i=0;i<jsonArray.size();i++){
                                if(i == answer){
                                    JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
                                    answers.add(jsonObject.getStr("value"));
                                    recordInfo.setAnswers(answers);
                                }
                            }
                            String result = answers.stream().map(n -> String.valueOf(n))
                                    .collect(Collectors.joining("-","{","}"));
                            recordInfo.setAnswer(result);
                        }
                    }
                }else if(question.getQuestionType() == 1) {//输入题
                    List<String> answers = new ArrayList<>();
                    answers.add(recordInfo.getAnswer());
                    recordInfo.setAnswers(answers);
                } else if(question.getQuestionType() == 2) {//多选题
                    if(StrUtil.isNotEmpty(question.getAnswerSection())){
                        JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                        if(jsonArray.size() > 0){
                            List<Integer> answerValues = JSONUtil.toList(recordInfo.getAnswer(),Integer.class);
                            List<String> answers = new ArrayList<>();
                            for (Integer index : answerValues){
                                for (int i = 0;i < jsonArray.size();i++){
                                    if(i == index){
                                        JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
                                        answers.add(jsonObject.getStr("value"));
                                    }
                                }
                            }
                            recordInfo.setAnswers(answers);
                            String result = answers.stream().map(n -> String.valueOf(n))
                                    .collect(Collectors.joining("-","{","}"));
                            recordInfo.setAnswer(result);
                        }
                    }
                }else if(question.getQuestionType() == 3) {//图片
                    List<String> answers = new ArrayList<>();
                    if(StrUtil.isNotEmpty(recordInfo.getAnswer())) {
                        List<String> answerTemps = JSONUtil.toList(recordInfo.getAnswer(), String.class);
                        for (String img : answerTemps){
                            img = imgUrl + img;
                            answers.add(img);
                        }
                    }
                    recordInfo.setAnswers(answers);
                }
            }
        });
        return dt;
    }


    @GetMapping("/exportExcel")
    public void testExprotExcel(@RequestParam("survey_id") Integer survey_id,
                                @RequestParam("town_id") Integer town_id,
                                @RequestParam("begin_date") String begin_date,
                                @RequestParam("end_date") String end_date,
                                HttpServletRequest request,
                                HttpServletResponse response){
        Map<String,Object> mapParam = new HashMap<>();
        Survey survey = surveyService.findById(survey_id);
        if(survey != null){
            QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
            qw.eq("survey_id",survey_id);
            mapParam.put("survey_id",survey_id);
            UserDO user = getUser();
            if(user.getUserType() == 7){
                if(user.getUserLevel() == 2){//镇
                    qw.eq("town_id",user.getTownId());
                    mapParam.put("town_id",user.getTownId());
                }else if(user.getUserLevel() == 3){//村
                    qw.eq("village_id",user.getVillageId());
                    mapParam.put("village_id",user.getVillageId());
                }else{
                    if(town_id!=null){
                        qw.eq("town_id",town_id);
                        mapParam.put("town_id",town_id);
                    }
                }
            }else{
                if(town_id!=null){
                    qw.eq("town_id",town_id);
                    mapParam.put("town_id",town_id);
                }
            }

            if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                qw.between("create_time",begin_date + " 00:00:00",end_date + " 23:59:59");
                mapParam.put("begin_time",begin_date + " 00:00:00");
                mapParam.put("end_time",end_date + " 23:59:59");
            }
            long totalCount = userRecordService.count(qw);
            int pageSize = 10;
            // 查询总数量和总页数
            long totalPages = totalCount / pageSize;
            if (totalCount % pageSize != 0) {
                totalPages++;
            }

            qw.orderByAsc("create_time");
            List<SurveyUserRecord> userRecordsNew = new ArrayList<>();
            for (int i = 0; i < totalPages;i++){
                int offset = (i) * pageSize;
//            List<SurveyUserRecord> userRecords = userRecordService.list(qw);
                List<SurveyUserRecord> userRecords = userRecordService.getExportListByUserIdPage(mapParam,offset,pageSize);
                if(CollUtil.isNotEmpty(userRecords)){
                    for (SurveyUserRecord userRecord : userRecords){

                        //判断当前是否需要重置 记录表
                        String tableName = userRecord.getRecordTableName();
                        // 配置表名
                        Map<String,Object> map = new HashMap<>();
                        map.put("survey_user_record_info", tableName);
                        RequestDataHelper.setRequestData(map);


                        QueryWrapper<SurveyUserRecordInfo> yinhuan = new QueryWrapper<>();
                        yinhuan.eq("record_id",userRecord.getId());
                        yinhuan.eq("question_id",5);
                        yinhuan.eq("user_id",userRecord.getWxUserId());
                        yinhuan.last("limit  1");
                        SurveyUserRecordInfo recordInfo0 = userRecordInfoService.getOne(yinhuan);
                        if(recordInfo0!=null){
                            SurveyQuestion question = surveyQuestionService.findById(recordInfo0.getQuestionId());
                            userRecord.setPaiChaYinHuan(getAnswer(question,recordInfo0));
                        }

                        String createTime = DateUtils.getTime(userRecord.getCreateTime());
                        userRecord.setCreateTimeStr(createTime);

                        QueryWrapper<SurveyUserRecordInfo> otherYinHuan = new QueryWrapper<>();
                        otherYinHuan.eq("record_id",userRecord.getId());
                        otherYinHuan.eq("question_id",6);
                        otherYinHuan.eq("user_id",userRecord.getWxUserId());
                        otherYinHuan.last("limit  1");
                        SurveyUserRecordInfo recordInfo1 = userRecordInfoService.getOne(otherYinHuan);
                        if(recordInfo1!=null){
                            SurveyQuestion question = surveyQuestionService.findById(recordInfo1.getQuestionId());
                            userRecord.setOtherYinHuan(getAnswer(question,recordInfo1));
                        }

                        Towns town = townsService.findById(userRecord.getTownId());
                        if(town!=null){
                            userRecord.setTownName(town.getTownName());
                        }
                        Towns village = townsService.findById(userRecord.getVillageId());
                        if(village!=null){
                            userRecord.setVillageName(village.getTownName());
                        }
                        UserDO manger = userService.findById(userRecord.getSysUserId());
                        if(manger!=null){
                            userRecord.setManagerName(manger.getName());
                            userRecord.setManagerPhone(manger.getMobile());
                        }
                    }
                    userRecordsNew.addAll(userRecords);
                }
            }
            ExcelUtils.writeExcel(response, userRecordsNew, SurveyUserRecord.class, System.currentTimeMillis() +"_调查问卷记录.xlsx");
        }
    }


    private String getAnswer(SurveyQuestion question,SurveyUserRecordInfo recordInfo){
        String answerRet = "";
        if(question.getQuestionType() == 0){//单选题
            if(StrUtil.isNotEmpty(question.getAnswerSection())){
                JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                if(jsonArray.size() > 0){
                    Integer answer = Integer.parseInt(recordInfo.getAnswer());
                    List<String> answers = new ArrayList<>();
                    for (int i=0;i<jsonArray.size();i++){
                        if(i == answer){
                            JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
                            answers.add(jsonObject.getStr("value"));
                            recordInfo.setAnswers(answers);
                        }
                    }
                    String result = answers.stream().map(n -> String.valueOf(n))
                            .collect(Collectors.joining("-","{","}"));
                    answerRet = result;
                }
            }
        } else if(question.getQuestionType() == 1) {//输入题
            answerRet = recordInfo.getAnswer();
        } else if(question.getQuestionType() == 2) {//多选题
            if(StrUtil.isNotEmpty(question.getAnswerSection())){
                JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                if(jsonArray.size() > 0){
                    List<Integer> answerValues = JSONUtil.toList(recordInfo.getAnswer(),Integer.class);
                    List<String> answers = new ArrayList<>();
                    for (Integer index : answerValues){
                        for (int i = 0;i < jsonArray.size();i++){
                            if(i == index){
                                JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
                                answers.add(jsonObject.getStr("value"));
                            }
                        }
                    }
                    recordInfo.setAnswers(answers);
                    String result = answers.stream().map(n -> String.valueOf(n))
                            .collect(Collectors.joining("-","{","}"));
//                    recordInfo.setAnswer(result);
                    answerRet = result;
                }
            }
        }
        return answerRet;
    }
}
